#!/bin/bash
# $1: 待检查deploy名称; $2: deploy所在namespace名称

count=60
success=0
IFS=','
while [ ${count} -gt 0 ]
do
        replicas=$(kubectl get deploy $1 -n $2  -o go-template="{{.status.replicas}},{{.status.readyReplicas}},{{.status.updatedReplicas}},{{.status.availableReplicas}}")
        echo "当前服务数量：${replicas}"
        arry=(${replicas})
        if [ "${arry[0]}" == "${arry[1]}" -a "${arry[1]}" == "${arry[2]}" -a "${arry[2]}" == "${arry[3]}" ];then
                echo "服务启动正常"
                success=1
                break
        fi
        sleep 2
        ((count--))
done

if [ "${success}" -ne 1 ];then
        echo "服务启动失败，更新失败日志:"
        pod_name=`kubectl get pods -n $2 | grep $1 | grep -v Running | awk '{print $1}' | head -n 1`
        kubectl logs ${pod_name} -n $2
        echo "正在进行回滚:"
        kubectl rollout undo deployment $1 -n $2
        echo "回滚结束，请检查更新失败日志"
        exit 1
fi